<?php
namespace App\Job;

use Hyperf\AsyncQueue\Job;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use App\Helper\SeoHelper;

class InsertrugbyJob extends Job
{
    protected $product_id;

    public function __construct(int $product_id)
    {
        $this->product_id = $product_id;
    }

    public function handle()
    {
        $logger = ApplicationContext::getContainer()
            ->get(LoggerFactory::class)
            ->get('tasklog', 'tasklog');

        $conn = Db::connection('irugbystore');

        $logger->info("开始处理商品", ['product_id' => $this->product_id]);

        try {
            $product = Db::table('products')
                ->where('id', $this->product_id)
                ->where('status', 1)
                ->first();
            if(!$product){
                $logger->info($this->product_id."没有商品信息", []);
                return;
            }

            $insertData = json_decode($product->date_added, true);
            if (json_last_error() !== JSON_ERROR_NONE || !is_array($insertData)) {
                Db::table('products')->where('id', $product->id)->update(['status' => 3]);

                $logger->info($this->product_id."date_added数据解析错误", []);
                return;
            }

            $model = $insertData['model'] ? trim($insertData['model']) : rand(1000,9999);
            $model = strtolower($model);

            $exists = $conn->select("SELECT product_id FROM oc_product WHERE model = ? LIMIT 1", [$model]);
            if (!empty($exists)) {
                Db::table('products')->where('id', $product->id)->update(['status' => 2]);

                $logger->info($this->product_id."-".$model."-模型已经存在", []);
                return;
            }

            $quantity = $viewed = rand(20, 60);
            $image = 'catalog/'.$model.'/'.basename($insertData['image'] ?? '');
            $size_chart = basename($insertData['size_chart'] ?? '');
            $langs = [1, 2];

            //开启事务
            $conn->beginTransaction();

            // oc_product
            $productId = $conn->table('oc_product')->insertGetId([
                'model' => $model,
                'sku' => '',
                'upc' => '',
                'ean' => '',
                'jan' => '',
                'isbn' => '',
                'mpn' => '',
                'location' => '',
                'quantity' => $quantity,
                'stock_status_id' => 7,
                'image' => $image,
                'manufacturer_id' => 0,
                'shipping' => 1,
                'price' => $insertData['price'] ?? '0.0000',
                'points' => 0,
                'tax_class_id' => 2,
                'date_available' => date('Y-m-d'),
                'weight' => '0.00000000',
                'weight_class_id' => 2,
                'length' => '0.00000000',
                'width' => '0.00000000',
                'height' => '0.00000000',
                'length_class_id' => 1,
                'subtract' => 0,
                'minimum' => 1,
                'sort_order' => 1,
                'status' => 0,
                'viewed' => $viewed,
                'date_added' => date('Y-m-d H:i:s'),
                'date_modified' => date('Y-m-d H:i:s'),
                'meta_robots' => '',
                'seo_canonical' => '',
                'size_chart' => $size_chart,
                'notice' => $product->webname.'.com'
            ]);

            // oc_product_description
            foreach ($langs as $val) {
                $conn->table('oc_product_description')->insert([
                    'product_id' => $productId,
                    'language_id' => $val,
                    'name' => $insertData['product_name'] ?? '',
                    'description' => $insertData['description'] ?? '',
                    'tag' => $insertData['tag'] ?? '',
                    'meta_title' => $insertData['meta_title'] ?? '',
                    'meta_description' => $insertData['meta_description'] ?? '',
                    'meta_keyword' => $insertData['meta_keyword'] ?? '',
                    'seo_keyword' => $insertData['meta_keyword'] ?? '',
                    'seo_h1' => $insertData['meta_keyword'] ?? '',
                    'seo_h2' => $insertData['meta_keyword'] ?? '',
                    'seo_h3' => $insertData['meta_keyword'] ?? '',
                    'image_title' => $insertData['product_name'] ?? '',
                    'image_alt' => $insertData['product_name'] ?? ''
                ]);
            }

            //images
            if(!empty($insertData['images'])){
                foreach ($insertData['images'] as $key => $val) {
                    $product_image_sort_order = (int)$key+1;
                    $product_image_image = basename($val ?? '');

                    if(!empty($product_image_image)){
                        $product_image_image = 'catalog/'.$model.'/'.$product_image_image;
                        $conn->table('oc_product_image')->insert([
                            'product_id' => $productId,
                            'image' => $product_image_image,
                            'sort_order' => $product_image_sort_order
                        ]);
                    }
                }
            }

            //oc_product_option、oc_product_option_value
            if(!empty($insertData['options'])){
                $option_value = [
                    'CHOOSE YOUR SIZE' => 11,
                    'PERSONALISE (Optional)' => 14,
                ];

                $option_desc_value = ['M' => 47, 'S' => 46, 'Your Name(12 max)' => 49, 'Your Number(2 max)' => 50, 'L' => 48, 'XL' => 51, '2XL' => 52, '3XL' => 53,
                    '4XL' => 54, '5XL' => 55, '3-4 Years' => 56, '5-6 Years' => 57, '7-8 Years' => 58, '9-10 Years' => 59, '11-12 Years' => 60, '13-14 Years' => 61,
                    'YS' => 62, 'YM' => 63, 'YL' => 64, 'YXL' => 65, 'Y2XL' => 66, 'Y3XL' => 67, '2-3 Years' => 68, '4-5 Years' => 69, '6-7 Years' => 70, '8-9 Years' => 71,
                    '10-11 Years' => 72, '12-13 Years' => 73
                ];

                foreach ($insertData['options'] as $val) {
                    $option_id = $option_value[$val['name']] ?? 0;
                    if($option_id > 0){
                        $product_option_id = $conn->table('oc_product_option')->insertGetId([
                            'product_id' => $productId,
                            'option_id' => $option_id,
                            'value' => '',
                            'required' => $val['required']
                        ]);

                        $option_value_price = ($option_id == 14) ? '5.0000' : '0.0000';
                        foreach ($val['values'] as $value) {
                            $conn->table('oc_product_option_value')->insert([
                                'product_option_id' => $product_option_id,
                                'product_id' => $productId,
                                'option_id' => $option_id,
                                'option_value_id' => $option_desc_value[$value['name']] ?? 0,
                                'quantity' => $quantity,
                                'subtract' => 0,
                                'price' => $option_value_price,
                                'price_prefix' => '+',
                                'points' => 0,
                                'points_prefix' => '+',
                                'weight' => '0.00000000',
                                'weight_prefix' => '+'
                            ]);
                        }
                    }
                }
            }

            //oc_product_special
            if(isset($insertData['special_price']) && !empty($insertData['special_price'])){
                $conn->table('oc_product_special')->insert([
                    'product_id' => $productId,
                    'customer_group_id' => 1,
                    'priority' => 1,
                    'price' => $insertData['special_price'],
                    'date_start' => '0000-00-00',
                    'date_end' => '0000-00-00'
                ]);
            }

            //oc_product_to_category
            if(!empty($insertData['categories'])){
                $categories_arr = ['All Stars' => 2, 'Kangaroos' => 3, 'Manly Warringah Sea Eagles' => 12, 'Melbourne Storm' => 13, 'Newcastle Knights' => 14,
                    'North Queensland Cowboys' => 15, 'Penrith Panthers	' => 16, 'South Sydney Rabbitohs' => 17, 'St George Illawarra Dragons' => 18,
                    'Sydney Roosters' => 19, 'Warriors1' => 20, 'Wests Tigers' => 21, 'Other' => 22, 'State of Origin' => 23, 'NSW Blues' => 24, 'QLD Maroons' => 25,
                    'Wallabies' => 26, 'Aviron Bayonnais' => 28, 'Biarritz Olympique' => 29, 'MHR Rugby' => 30, 'National Rugby Union Team' => 31,
                    'RCT Toulon Rugby' => 33, 'Stade Francais Rugby' => 34, 'Stade Rochelais' => 35, 'Stade Toulousain' => 36, 'Union Bordeaux Begles' => 37,
                    'Argentina' => 39, 'Croatia' => 40, 'FIJI' => 41, 'Georgia' => 42, 'India' => 43, 'Italy' => 44, 'Jamaica' => 45, 'Japan' => 46, 'Lebanon' => 47,
                    'Malaysia' => 48, 'Papua New Guinea ' => 49, 'Portugal' => 50, 'Samoa' => 51, 'Spain' => 52, 'Tonga' => 53, 'USA' => 54, 'Country Gear' => 56,
                    'Leinster' => 57, 'Munster' => 58, 'Ulster' => 59, 'All Blacks' => 61, 'Blackcaps' => 62, 'Blues' => 63, 'Canterbury' => 64, 'Chiefs' => 65,
                    'Crusaders' => 66, 'Highlanders' => 67, 'Hurricanes' => 68, 'Kiwis' => 69, 'Moana Pasifika' => 70, 'Northland' => 71, 'Otago' => 72, 'Others' => 73,
                    'Tasman Mako' => 74, 'Warriors' => 75, 'Cheetahs' => 77, 'Lions' => 78, 'Sharks' => 79, 'Southern Kings' => 80, 'Springboks' => 81, 'Stormers' => 82,
                    'Vodacom Bulls' => 83, 'Barbarians' => 85, 'Bath Rugby' => 86, 'Bristol Bears' => 87, 'British and Irish Lions' => 88, 'Cardiff Blues' => 89,
                    'Edinburgh' => 90, 'England National Rugby Team' => 91, 'Exeter Chiefs' => 92, 'Glasgow Warriors' => 93, 'Great Britain Lions' => 94, 'Harlequins' => 95,
                    'Leeds Rhinos' => 96, 'Newcastle Falcons' => 97, 'Northampton Saints' => 98, 'Ospreys' => 99, 'Sale Sharks' => 100, 'Saracens' => 101,
                    'Scotland National Rugby Team' => 102, 'Super League' => 103, 'Hull FC' => 104, 'Hull Kingston Rovers' => 105, 'St Helens RLFC' => 106,
                    'Wigan Warriors' => 107, 'Wales National Rugby Team' => 108, 'Australia' => 1, 'NRL Telstra Premiership' => 4, 'Parramatta Eels' => 5,
                    'Brisbane Broncos' => 6, 'Canberra Raiders' => 7, 'Canterbury-Bankstown Bulldogs' => 8, 'Cronulla-Sutherland Sharks' => 9, 'Gold Coast Titans' => 11,
                    'Racing 92' => 32, 'World Cup' => 109, 'Ireland' => 55, 'South Africa' => 76, 'United Kingdom' => 84, 'New Zealand' => 60, 'Dolphins' => 10,
                    'France' => 27, 'International' => 38
                ];
                foreach ($insertData['categories'] as $val) {
                    $category_id = $categories_arr[$val['name']] ?? 0;
                    if($category_id > 0){
                        $conn->table('oc_product_to_category')->insert([
                            'product_id' => $productId,
                            'category_id' => $category_id
                        ]);
                    }
                }
            }

            //oc_product_to_layout
            $conn->table('oc_product_to_layout')->insert([
                'product_id' => $productId,
                'store_id' => 0,
                'layout_id' => 0
            ]);

            //oc_product_to_store
            $conn->table('oc_product_to_store')->insert([
                'product_id' => $productId,
                'store_id' => 0
            ]);

            //oc_seo_url
            $seoUrl = SeoHelper::generateSeoUrl($insertData['product_name']);
            foreach ($langs as $val) {
                $conn->table('oc_seo_url')->insert([
                    'store_id' => 0,
                    'language_id' => $val,
                    'query' => 'product_id='.$productId,
                    'keyword' => $seoUrl
                ]);
            }

            //products
            Db::table('products')->where('id', $product->id)->update(['status' => 2]);

            $conn->commit();

            $logger->info("商品处理完成", ['product_id' => $this->product_id]);
        } catch (\Throwable $e) {
            if ($conn->getPdo()->inTransaction()) {
                $conn->rollBack();
            }

            $logger->error("InsertrugbyJob 系统错误", [
                'product_id' => $this->product_id,
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }

    public function shouldQueue(): bool
    {
        return true;
    }
}
